<template>
  <div>
    <div style="margin-bottom: 15px;display: flex;justify-content: space-between">
      <el-alert
          style="width: 80%"
          :title="$t('配置可借周期时，请务必配置一款结清0次可借的周期产品，避免导致用户无法借款') + '!'"
          type="info"
          show-icon
          :closable="false">
      </el-alert>
      <el-button type="primary" @click="addTerm" v-show="panePermiss[1048]">{{ $t('新增') }}</el-button>
    </div>
    <Table :tableData="tableData" :table-column="tableColumn" :page="page" @handleSizeChange="handleSizeChange"
           @handleCurrentChange="handleCurrentChange">
      <template slot="status" slot-scope="{row}">
        <el-switch @change="changeStatus(row)"
                   :disabled="!panePermiss[1054]"
                   :value="row.status === 1"></el-switch>
      </template>
      <template slot="canLoan" slot-scope="{row}">
        {{ row.canLoan === 0 ? $t('是') : $t('否') }}
      </template>
      <template slot="handle" slot-scope="{row}">
        <el-button type="text" v-show="panePermiss[1051]" @click="editTerm(row)">{{ $t('编辑') }}</el-button>
        <el-button type="text" @click="deleteProduct(row)" v-show="panePermiss[1056]">{{ $t('删除') }}
        </el-button>
      </template>
    </Table>
    <Dialog :visible.sync="visible.show" :title="visible.title" @cancel="visible.show = false" @close="clearForm"
            @confirm="visibleConfirm">
      <el-form label-width="120px">
        <el-form-item :label="$t('可借周期')">
          <el-select :disabled="visible.type === 'edit'" v-model="form.loanTerm">
            <el-option v-for="item in selectTermList" :key="item" :value="item" :label="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('结清几次可借')">
          <el-input v-model="form.refundNum"/>
        </el-form-item>
        <el-form-item :label="$t('可借下一周期时该周期是否隐藏')" label-width="220px">
          <div style="line-height: 32px">
            <el-switch v-model="form.canLoan"></el-switch>
          </div>
        </el-form-item>
      </el-form>
    </Dialog>
  </div>
</template>

<script>
import qs from "qs";

export default {
  name: "periodConfig",
  props: ['panePermiss'],
  data() {
    return {
      tableData: [],
      tableColumn: [
        {label: this.$t('可借周期'), prop: 'loanTerm', minWidth: 100},
        {label: this.$t('结清几次可借'), prop: 'refundNum', minWidth: 150},
        {label: this.$t('借下一周期时隐藏'), slot: 'canLoan', minWidth: 150},
        {label: this.$t('创建时间'), prop: 'inputTime', minWidth: 100},
        {label: this.$t('更新时间'), prop: 'updateTime', minWidth: 100},
        {label: this.$t('状态'), slot: 'status', minWidth: 100},
        {label: this.$t('操作'), slot: 'handle', minWidth: 100},
      ],
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      visible: {
        type: '',
        title: '',
        show: false,
      },
      selectTermList: [],
      form: {
        loanTerm: null,
        refundNum: null,
        canLoan: true
      }

    }
  },
  created() {
    this.getTableData()
  },
  methods: {
    async getTableData() {
      const res = await this.$get('loanTerm/queryList', {...this.page, productName: this.$route.query.productName})
      if (res.code === 1) {
        const {list, total} = res.data
        this.tableData = list
        this.page = {
         total
        }
      }
    },
    addTerm() {
      this.selectTerm()
      this.visible = {
        type: 'add',
        title: this.$t('新增可借周期'),
        show: true,
      }
    },
    async selectTerm() {
      const res = await this.$get('loanTerm/queryTermList', {
        productName: this.$route.query.productName
      })
      if (res.code === 1) {
        this.selectTermList = this.removalTerm(res.data) || []
      }
    },
    async changeStatus({status, id}) {
      const res = await this.$post('loanTerm/updateTerm', qs.stringify({
        id,
        status: status === 1 ? 0 : 1,
      }))
      if (res.code === 1) {
        this.$message.success(this.$t('修改成功'))
        this.getTableData()
      }
    },
    async deleteProduct({id}) {
      this.$confirm(this.$t('确定删除?'), this.$t('提示'), {
        type: 'warning'
      }).then(async () => {
        const res = await this.$post('loanTerm/deleteById', qs.stringify({id}))
        if (res.code === 1) {
          this.$message({
            type: 'success',
            message: this.$t('删除成功')
          });
          this.getTableData()
        }
      }).catch(() => {
      });
    },
    // 去除重复天数
    removalTerm(arr) {
      let obj = {}
      let res = []
      arr.forEach(item => {
        if (!obj[item]) {
          res.push(item)
          obj[item] = true
        }
      })
      obj = {}
      return res
    },
    handleSizeChange(val) {
      this.page.pageSize = val
      this.getTableData()
    },
    handleCurrentChange(val) {
      this.page.pageNum = val
      this.getTableData()
    },
    clearForm() {
      this.form = {
        loanTerm: null,
        refundNum: null,
        canLoan: true
      }
    },
    editTerm(row) {
      this.selectTerm()
      this.visible = {
        type: 'edit',
        title: this.$t('编辑可借周期'),
        show: true,
      }
      this.form = {
        ...row,
        canLoan: row.canLoan === 0
      }
    },
    async visibleConfirm() {
      const {loanTerm, refundNum, id, canLoan} = this.form
      let params = {
        loanTerm, refundNum,
        canLoan: canLoan ? 0 : 1,
        productName: this.$route.query.productName
      }
      let url = ''
      let message = ''
      if (this.visible.type === 'add') {
        url = 'loanTerm/addTerm'
        message = this.$t('新增成功')
      } else {
        params['id'] = id
        url = 'loanTerm/updateTerm'
        message = this.$t('修改成功')
      }
      const res = await this.$post(url, qs.stringify(params))
      if (res.code === 1) {
        this.visible.show = false
        this.$message.success(message)
        this.getTableData()
      }
    }
  }
}
</script>

<style scoped>

</style>
